from fastapi import FastAPI, UploadFile, File, Form
import uvicorn
from fastapi.middleware.cors import CORSMiddleware

from db.curd import connect
from db.model import User



app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],  # 允许的前端地址
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.post('/file')
async def down_file(file: UploadFile = File(...)):
    contents = await file.read()
    with open("./tmp/" + file.filename, "wb") as f:
        f.write(contents)


@app.post('/regin')
async def regin(username: str = Form(), password: str = Form()):
    db = connect.db()
    new_user_info = User(username=username, password=password)
    try:
        db.add(new_user_info)
        db.commit()
        db.close()
        return {"code": 200, 'message': '成功'}
    except Exception as e:
        return {"code": 400, 'message': '注册失败'}


@app.post('/login')
async def login(username: str = Form(), password: str = Form()):
    db = connect.db()
    res = db.query(User).filter(User.username == username, User.password == password).all()
    if res is None:
        return {"code": 400, "message": "请检查用户名密码"}
    else:
        return {"code": 200, "message": "登陆成功"}


if __name__ == '__main__':
    uvicorn.run(app, host="localhost", port=8080)
